//
//  PayHtm5VC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/3/17.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "PayHtm5VC.h"
//#import "UIViewController+BackButtonHandler.h"
#import "NHCourseDetailVC.h"
#import "HELOrderListVC.h"
#import "HELPayResultVC.h"
//#import <AlipaySDK/AlipaySDK.h>
@interface PayHtm5VC ()


@property (nonatomic,  strong) MBProgressHUD *hud;

@property (nonatomic,  strong) NSString *payInfor;

@end

@implementation PayHtm5VC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    NoficationCenter_Obeserve(payResult:, Alipay_Result_noti);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStyleDone target:self action:@selector(backToVC)];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    //发送刷新通知
    [self wsj_hideLodingGif];
    NoficationCenter_post(RefreshCourseDetail);
    NoficationCenter_post(RefreshCourseContent);
    NoficationCenter_post(RefreshOrderlist);
    
}
//- (BOOL)navigationShouldPopOnBackButton{
//    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        NSLog(@"%@, ----%@",obj.class , @(idx));
//        if ([obj isKindOfClass:[NHCourseDetailVC class]]) {
//            [self.navigationController popToViewController:obj animated:YES];
//            NoficationCenter_post(RefreshCourseDetail);
//            NoficationCenter_post(RefreshCourseContent);
//            return ;
//        }
//        if ([obj isKindOfClass:[HELOrderListVC class]]) {
//            NoficationCenter_post(RefreshOrderlist);
//            NoficationCenter_post(RefreshCourseContent);
//            [self.navigationController popToViewController:obj animated:YES];
//        }
//        
//    }];
//    return NO;
//
//}


//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    
//    NSURLRequest *request = navigationAction.request;
// 
//    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
//    NSString* orderInfo = [[AlipaySDK defaultService] fetchOrderInfoFromH5PayUrl:[request.URL absoluteString]];
//    if (orderInfo.length > 0) {
//        // 此处应该调用SDK提供的支付接口进行支付
//        // 参考后文
//        
//      
//        
//        actionPolicy = WKNavigationActionPolicyCancel;
//    }
//    actionPolicy = WKNavigationActionPolicyAllow;    //这句是必须加上的，不然会异常
//    decisionHandler(actionPolicy);
//}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [super webView:webView didFinishNavigation:navigation];
    NSString *doc = @"document.body.outerHTML";
    [webView evaluateJavaScript:doc
                     completionHandler:^(id  _Nullable htmlStr, NSError * _Nullable error) {
                         if (error) {
                             NSLog(@"JSError:%@",error);
                         }
                         
                         
                         
                         NSLog(@"html:%@",htmlStr);
                     }] ;
    weakSelf_define;
    [webView evaluateJavaScript:@"getStatus()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
       
        if ([response isKindOfClass:[NSString class]]) {
            if ([response isEqualToString:@"not_support_pay"]) {
                HELPayResultVC * vc =[HELPayResultVC new];
                [vc setresult:-1 isFromCourse:[weakSelf isfromeCourse]];
                vc.clickBlock  =^(NSInteger index){
                    if (index == 0) {
                        [weakSelf backToVC];
                    }
                    
                };
                vc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64);
                [weakSelf addChildViewController:vc];
                [weakSelf.view addSubview:vc.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf backToVC];
                });
                
            }else if([response isEqualToString:@"pay"]){
                [webView evaluateJavaScript:@"getPayInfo()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                    
                    weakSelf.payInfor = response;
                    [weakSelf call_aliPay];
                   
                    
                    
                }];
            }else if([response isEqualToString:@"no_pay"]){
               
                cwqHudSuccess(@"参加课程成功!");
                
                [weakSelf backToVC];
                
            
            }
        }
        
    }];
  
}


- (void)call_aliPay{
    //调出支付宝
    cwqHud(self.view);
    self.hud = hud;
    
    // NOTE: 调用支付结果开始支付
//    [[AlipaySDK defaultService] payOrder:self.payInfor fromScheme:@"com.shengshi.NursingAssociation" callback:^(NSDictionary *resultDic) {
//        
//    }];
}


- (void)backToVC{
    
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@, ----%@",obj.class , @(idx));
        if ([obj isKindOfClass:[NHCourseDetailVC class]]) {
            [self.navigationController popToViewController:obj animated:YES];
            NoficationCenter_post(RefreshCourseDetail);
            NoficationCenter_post(RefreshCourseContent);
            return ;
        }
        if ([obj isKindOfClass:[HELOrderListVC class]]) {
            NoficationCenter_post(RefreshOrderlist);
            NoficationCenter_post(RefreshCourseContent);
            [self.navigationController popToViewController:obj animated:YES];
        }
        
    }];
    
}
- (BOOL)isfromeCourse{
    
    __block  BOOL is = NO;
    [self.navigationController.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isKindOfClass:[NHCourseDetailVC class]]) {
            is = YES;
            return ;
        }
        
        
    }];
    
    return is;
    
}



- (void)payResult:(NSNotification *)not{
    [self.hud hide:YES];
    
    weakSelf_define;
    NSDictionary *dic = not.userInfo;
    NSLog(@"reslut = %@",not.userInfo);
    HELPayResultVC *vc =[HELPayResultVC new];
    //支付成功//
    if (dic[@"resultStatus"] && [dic[@"resultStatus"] integerValue] == 9000) {
        [vc setresult:1 isFromCourse:[self isfromeCourse]];
        vc.clickBlock  =^(NSInteger index){
            if (index == 0) {
                [weakSelf backToVC];
            }
            
        };
        [self addChildViewController:vc];
        vc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64);
        [self.view addSubview:vc.view];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self backToVC];
        });
        
        
    }else{
        [vc setresult:0 isFromCourse:[self isfromeCourse]];
        vc.clickBlock  =^(NSInteger index){
            if (index == 0) {
                [weakSelf call_aliPay];
            }
            
        };
        vc.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64);
        [self addChildViewController:vc];
        [self.view addSubview:vc.view];
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [UIView animateWithDuration:.35 animations:^{
//                vc.view.alpha = 0;
//            } completion:^(BOOL finished) {
//                [vc.view removeFromSuperview];
//                [vc removeFromParentViewController];
//            }];
//        });
        
    }
    
}
@end
